		var datagrid;
		var editRow = undefined;//行编辑标志
		var BASE_URL = '/cnscecms-admin/employee/';
		$(function() {
			
			initDatagrid();
		});
		
		function initDatagrid(){
			
			datagrid = $('#datagrid').datagrid({
				title : '',
				iconCls : 'icon-save',
			    pagination : true,//进度条
				pageSize : 10,//每页显示10条
				pageList : [ 10, 20, 30, 40, 50 ],//选择每页显示条数 
    	     	fit : true,
				fitColumns : true,//设置false页面变窄时显示横向滚动条
				nowrap : true,//设置为false表格内容自动折行但是影响性能
				border : false,
				striped : true,
				idField : 'employeeId',//翻页选择标记（便于多页删除）
		  
				remoteSort : false,
				url : BASE_URL + 'list.do',
				columns : [ [{
					title : '选择框',
					field : 'box',
					width : 90,
					checkbox:true,	
				 }, {
					field:"employeeId",title:'员工编号',width:100,sortable:true,hidden:true,
				}, {
					field:"employeeName",title:'姓名',width:80,sortable:true,editor:{type:'validatebox',
						options : {
							required : true
						} }
				}, {
					field:"employeeDepartment",title:'工作单位',width:200,sortable:true,
					formatter: function(value,row,index){return row.departmentName;},
					editor:{type:'combotree',
							options:{url:'/cnscecms-admin/organization/listOSTree.do',//'organization_structure.json',//
//									valueField:"id",
//									textField:'name',
									parentField:'superior',
//									formatter:function(node){return node.name},
//									multiple:false
								}
						}
				},{
					field:"employeeDuties",title:'职务',width:120,sortable:true,editor : {
						type : 'combobox',
						options : {
							url:"/cnscecms-admin/basicdataset/getBasicDataSetbyParentId.do?parentId=3073",
							valueField:"chineseName",
							textField:"chineseName"
						}
					}

				},{
					field:"workGroup",title:'组委会工作部门',width:120,sortable:true,
					editor : {
						type : 'combobox',
						options : {
							url:"/cnscecms-admin/basicdataset/getBasicDataSetbyParentId.do?parentId=3058",
							valueField:"chineseName",
							textField:"chineseName"
						}
					}
				},{
					field:"workGroupDuties",title:'组委会职务',width:120,sortable:true,
					editor : {
						type : 'combobox',
						options : {
							url:"/cnscecms-admin/basicdataset/getBasicDataSetbyParentId.do?parentId=3068",
							valueField:"chineseName",
							textField:"chineseName"
						}
					}

				},{
					field:"employeeCellPhone",title:'手机',width:120,sortable:true,editor:{type:'text'}
				},{
					field:"employeeOfficePhone",title:'电话',width:120,sortable:true,editor:{type:'validatebox',options : {
						validType : ['number']
					}}
				},{
					field:"email",title:'邮箱',width:120,sortable:true,editor:{type:'validatebox',options:{validType:['email']}}
				},{
					field:"fax",title:'传真',width:120,sortable:true,editor:{type:'validatebox',options : {
						validType : ['number']
					}}
				},{
					field:"comment",title:'备注',width:120,sortable:true,editor:{type:'validatebox',options : {
						validType : ['number']
					}}
				}/*, {
					field:"account",title:'登陆帐号',width:80,sortable:true,editor:{type:'validatebox'}
				}, {
					field:"password",title:'密码',width:80,sortable:true,editor:{type:'validatebox'}
				}*/
				,{
					field:"employeeQq",title:'QQ',width:120,sortable:true,editor:{type:'text'}
//				},{
//				   field:"employeeCreator",title:'录入人',width:80,sortable:true,editor:{type:'text'}
//				},{
//				   field:"employeeAccessGroup",title:'权限组',width:80,sortable:true,editor:{type:'text'}
//				},{
//				   field:"employeeCreationTime",title:'录入时间',width:150,sortable:true, 
//				},{
//				   field:"employeeStatus",title:'状态',width:80,sortable:true,editor:{type:'text'}
				} ] ],//合并单元格
				toolbar : [ '-',{
					id:"RESOURCE_4040200",
					text : '增加',
					iconCls : 'icon-add',
					handler : function() {
							add();
					}

				}, '-', {
					id:"RESOURCE_4040400",
					text : '删除',
					iconCls : 'icon-remove',
					handler : function() {
						remove();
					}
				}, '-', {
					id:"RESOURCE_4040300",
					text : '修改',
					iconCls : 'icon-edit',
					handler : function() {
						edit();
					}
				}, '-', {
					text : '保存',
					iconCls : 'icon-save',
					handler : function() {
						endEdit();
						save();
					}
				}, '-',   {
					text : '取消',
					iconCls : 'icon-undo',
					handler : function() {
						redoall();
					}
				}, '-' , {
					text : '导出Excel',
					iconCls : 'icon-down',
					handler : function() {
						exportExcel();
					}
				}, '-', {
					text : '发送短信',
					iconCls : 'icon-smssend',
					handler : function() {
					
						showPopWindow(SMS_DIV,"发送短信",450,300);
					}
				}, '-'  ],
				//onClickRow:autoChange,
				onAfterEdit : function() {
					//endEdit();
					save();
					datagrid.datagrid("acceptChanges");
					datagrid.datagrid("unselectRow", editRow);
					editRow = undefined;
				},
				onDblClickRow : function(rowIndex, rowData) {//双击编辑行
					if (editRow != undefined) {
					    if($('.validatebox-invalid').length>0)//判断双击行切换编辑的时候是否有必填项为空
							{
							$.messager.show('警告','必填信息不能为空！');
							return;
							}
						datagrid.datagrid('endEdit', editRow);
				}
					if (editRow == undefined) { 
						//var rows = datagrid.datagrid('getRows');
						datagrid.datagrid('beginEdit', rowIndex);
						editRow = rowIndex ;
						datagrid.datagrid('selectRow',editRow);//选中编辑行
						bindBlurToCellRow(editRow);
						
					}
				}
			});
		}
		

		function smsSend(){
			
			
			doSmsSend( getSelectionCellPhones());
			
		}

		function getSelectionCellPhones(){
			
			if($('.datagrid-row-editing').length>0){
		        $.messager.show('提示','存在未保存数据，不能执行该操作，取消编辑请点击“取消”！');
		        return;
		    }
			
			var rows = datagrid.datagrid('getSelections');//获得选中项
			
			if (rows.length == 0) {
				return [];
			}
			
			var mobiles = [];
			for (var i = 0; i < rows.length; i++) {
				if(rows[i].employeeCellPhone == "" || rows[i].employeeCellPhone == undefined)
				;
				else
					mobiles.push(rows[i].employeeCellPhone);
			}
			
			return mobiles;
		}
			
//			function unitFormatter(value, rowData, rowIndex) {  
//			    if (value == 0) {  
//			        return "";  
//			    }  
//			    for (var i = 0; i < unitJSON.length; i++) {  
//			        if (unitJSON[i].value == value) {  
//			            return unitJSON[i].name;  
//			        }  
//			    }  
//			    return value;  
//			}     
			
			
			function endEdit() {
				var rows = datagrid.datagrid('getRows');
				for ( var i = 0; i < rows.length; i++) {
					datagrid.datagrid('endEdit', i);
				}
			}
	
			function exportExcel() {

				var queryPara =  sy
				.serializeObject($('#searchForm'));
				
				var url = BASE_URL+"exportExcel.do?queryPara=" + JSON.stringify(queryPara) ;
				window.location.href = url;
			}
			
			function add() {
				if (editRow != undefined)  {
				    datagrid.datagrid('endEdit', editRow);
				    $.messager.show({
							title : '提示',
							msg : '必填信息不能为空'
						});
				}
				//datagrid.datagrid('appendRow', {//末尾增加

				//});
				if (editRow == undefined) {//判断一次只能增加一行
				datagrid.datagrid('insertRow', {//首行增加
					index : 0,
					row : {

					}

				});
				var rows = datagrid.datagrid('getRows');
				//datagrid.datagrid('beginEdit', rows.length - 1);//开启行编辑模式，在末尾插入index索引从零开始，因此减1
				datagrid.datagrid('beginEdit', 0);
				editRow = 0;

				bindBlurToCellRow(editRow);
//				datagrid.datagrid('selectRow',editRow);//选中编辑行
//						var ed = $('#datagrid').datagrid('getEditors', editRow);
//				        for (var i = 0; i < ed.length; i++)
//				        {
//					        var e = ed[i];
//					        if(e.field == "dptCode")
//					        {
//						        $(e.target).bind("keyup",function(){
//		                 	        return toUpper($(this));
//		            	        }).bind("change", function(){
//		                 	        return toUpper($(this));
//		            	        });
//					        }
//				        }
			    }
			}
			function remove() {
				if($('.datagrid-row-editing').length>0){
                    $.messager.show('提示','存在未保存数据，不能执行删除操作，取消编辑请点击“取消”！');
                    return;
                    }
				var rows = datagrid.datagrid('getSelections');//获得选中项
				 
				if (rows.length > 0) {
					$.messager.confirm('请确认', '您确定要删除当前选择的所有项吗？', function(b) {
						if (b) {
							var ids = [];
							for (i = 0; i < rows.length; i++) {
								ids.push(rows[i].employeeId);
							}
							console.info(ids.join(','));
							$.ajax({
								url : BASE_URL + 'delete.do',
								data : {
									ids : ids.join(',')
								},
								dataType : 'json',
								success : function(r) {
									datagrid.datagrid('load');
									datagrid.datagrid('unselectAll');
									$.messager.show({
										title : '提示',
										msg : '删除成功'
									});
								}
							});
						}
					});
					//console.info(rows)
				} else {
					$.messager.alert('提示', '请选择要删除的记录', 'error');
				}
			}
			function edit() {
				var rows = datagrid.datagrid('getSelections');
				if (rows.length > 1){
				    $.messager.show('提示','一次只能修改一条数据！');
				    return;
				}
			 
				if (rows.length == 1) {
					if (editRow != undefined) {
						datagrid.datagrid('endEdit', editRow);
					}
					if (editRow == undefined) {    
						var index =datagrid.datagrid('getRowIndex', rows[0]);
						datagrid.datagrid('beginEdit', index);
						editRow = index;
						datagrid.datagrid('unselectAll');
						bindBlurToCellRow(editRow);
					}
				}
          }
			
			function save() {
				var changeRows = datagrid.datagrid('getChanges');

				if($('.validatebox-invalid').length!=0){
					$.messager.alert('警告','请按照提示输入正确信息！','error');
					return false;
				}
				if (datagrid.datagrid('getChanges').length) {
					var inserted = datagrid.datagrid('getChanges', "inserted");
					var updated = datagrid.datagrid('getChanges', "updated");
					var effectRow = new Object();
					if (inserted.length) {
						effectRow["inserted"] = JSON.stringify(inserted);
					}
					if (updated.length) {
						effectRow["updated"] = JSON.stringify(updated);
					}
					$.post(BASE_URL + 'save.do', effectRow,
							function(data) {
								if (data == 'success') {

									$.messager.show({
										title : '提示',
										msg : '保存成功'
									});
//									datagrid.datagrid('reload',{}); 
								}else if(data == 'error 用户手机号或邮箱已存在') {
									$.messager.alert('提示','用户手机号或邮箱已存在，请修改后重新保存！','error');
								
								}
							}, "JSON").error(function() {
						$.messager.show({
							title : '提示',
							msg : '保存失败'
						});
					});
				}
			}
			function redoall() {
				editRow = undefined;
				datagrid.datagrid('rejectChanges');
				datagrid.datagrid('reload',{});
				datagrid.datagrid('unselectAll');
			}
			function redo() {
				var rows = datagrid.datagrid("getSelections"); //获取你选择的所有行
				if (rows) {
					$.messager.confirm('请确认', '您确定要取消当前编辑的项吗？', function(b) {
						if (b) {
							for (i = 0; i < rows.length; i++) {
								var index = datagrid.datagrid('getRowIndex',rows[i]);//获取某行的行号     
								datagrid.datagrid('deleteRow', index);
							}
						}
					})
				}
				if (!rows) {
					editRow = undefined;
					datagrid.datagrid('rejectChanges');
					datagrid.datagrid('unselectAll');
				}
			}
			
			 
//      function toUpper(validatebox)//小写转大写
//      {
//          var currentWords = $(validatebox).val();
//          console.info(currentWords)
//          if (currentWords)
//          {
//              $(validatebox).val($(validatebox).val().toUpperCase());
//          }
//      }

			function bindBlurToCellRow(rowIndex){
				datagrid.datagrid('selectRow',rowIndex);//选中编辑行

			 $( datagrid.datagrid('getEditors', rowIndex)).each(function(index,editor){
			 	
			 	//邦定 姓名列单元格事件
			 	if(editor.field == "employeeName" ){
			 	
			 		editor.target.bind('blur',function () {
			 			
			 			var employeeName = editor.target.val();
			 			if(employeeName.length > 2 && isExistEmployeeByName(employeeName)){
			 				
			 				alert(employeeName+ "已存在！");
			 				editor.target.val("");
			 				editor.target.focus();
			 			}
			 		   
			 	
			 		 });
			 	}
			 	if( editor.field == "employeeCellPhone"){
			 	
			 		editor.target.bind('blur',function () {

			 			var employeeCellPhone = editor.target.val();
			 			if(employeeCellPhone.length == 11 && isExistEmployeeByCellPhone(employeeCellPhone)){
							
			 				
							alert(employeeCellPhone + "手机号已存在！");
							editor.target.val("");
			 				editor.target.focus();
						}
					   
				

			 		 });
			 	}
			 		
				});
			}

			//设置已存在的报名者信息
			function isExistEmployeeByName(employeeName){

				var employeeJSON = $.util.requestAjaxData(BASE_URL + 'getByEmployeeName.do',{"employeeName":employeeName});
				if($.isEmptyObject(employeeJSON) )
					return false;
				else{}
					return true;
			}

			//设置已存在的报名者信息
			function isExistEmployeeByCellPhone(employeeCellPhone){

				var employeeJSON = $.util.requestAjaxData(BASE_URL + 'getByCellPhone.do',{"cellPhone":employeeCellPhone});
				if($.isEmptyObject(employeeJSON)  )
					return false;
				else
					return true;
			}

		
		
	
		/**
		 * 查询，将查询参数不为空的放入JSON传入后台,该写法支持模糊查询
		 */
		function searchEmployee(){
			$('#datagrid').datagrid('load', sy.serializeObject($('#searchForm')));
		    }
		
		/**
		 * 点击清空按钮触发事件，注意将查询JSON置为空
		 */
		function clearEmployee(){
		    $('#searchForm').form('clear');
		    json = {};//将查询参数JSON置为空
		    $('#datagrid').datagrid('load', {});
		}